<template>
  <tableRender />
</template>

<script setup name="BwtTable" lang="jsx">
import uniq from "lodash-es/uniq";
import { judgeNullOrEmpty } from "@/utils/index.js";
const props = defineProps({
  api: {
    type: Function,
  },
  apiCB: {
    type: Function,
  },
  params: {
    type: Object,
    default: () => ({}),
  },
  columns: {
    type: Array,
    default: () => [],
  },
  localData: {
    type: Array,
    default: () => [],
  },
  pollInterval: {
    type: Number,
    default: 0,
  },
  paginationable: {
    type: Boolean,
    default: true,
  },
  rowKey: {
    type: [String, Function],
  },
  rowClassName: {
    type: [String, Function],
  },
  rowStyle: {
    type: [String, Function],
  },
  headerRowClassName: {
    type: [String, Function],
  },
  highlightCurrentRow: {
    type: Boolean,
  },
  size: {
    type: String,
  },
  height: {
    type: String | Number,
  },
  lazy: {
    type: Boolean,
  },
  load: {
    type: Function,
  },
  treeProps: {
    type: Object,
  },
  initPageSize: {
    type: Number,
    default: 10,
  },
  headerCellStyle: {
    type: Object,
    default: () => ({
      background:'#F7F8FF',
      color:'#333',
      fontWeight: 550,
      fontSize: '12px',
      height: '50px'
    })
  }
});

var uid = ref(0);
var loading = ref(false);
var page = ref(1);
var pageSize = ref(10);
var total = ref(10);
var data = ref([]);
var timer = null;

const { proxy } = getCurrentInstance();
const emit = defineEmits();

var pageSizes = computed(() => {
  const pageSizes = [
    10,
    20,
    30,
    40,
    50,
    100,
    pageSize.value,
    props.initPageSize,
  ].sort((a, b) => a - b);
  return uniq(pageSizes);
})

onMounted(() => {
  search()
})
onUnmounted(() => {
  timer && clearTimeout(timer)
})

function search() {
  uid.value++;
  page.value = 1;
  return getData();
}

function getData() {
  return new Promise((resolve, reject) => {
    nextTick(() => {
      if (typeof props.api === "function") {
        loading.value = true;
        fetch().then(resolve).catch(reject);
      } else {
        data.value = props.localData;
        resolve();
      }
    });
  });
}

function fetch() {
  let params = {
    page_no: page.value,
    page_size: pageSize.value,
    ...props.params,
  };
  let handleParams = judgeNullOrEmpty(params);
  const pollInterval = () => {
    timer && clearTimeout(timer);
    if (props.pollInterval) {
      timer = setTimeout(() => fetch(), props.pollInterval);
    }
  };
  let fetchUid = uid.value;
  const fetch = props.api(handleParams);
  fetch
    .then((rsp) => {

    console.log('rsp=======', rsp)
      // 只显示最后一次操作的数据
      if (fetchUid === uid.value) {
        total.value = rsp.total_count;
        data.value = rsp.rows || [];
      }
      props.apiCB && props.apiCB(rsp.rows);
      loading.value = false;
      pollInterval();
    })
    .catch(() => {
      loading.value = false;
      pollInterval();
    });
  return fetch;
}

function formatter(row, column, cellValue, index) {
  return cellValue === undefined || cellValue === null ? "-" : cellValue;
}

function refresh() {
  uid.value++;
  return getData();
}

function clearSelection() {
  proxy.$refs.table.clearSelection();
}
function toggleRowSelection(...args) {
  proxy.$refs.table.toggleRowSelection(...args);
}
function setCurrentRow(...args) {
  proxy.$refs.table.setCurrentRow(...args);
}

watch(page, (newVal, oldVal) => {
  handlePageChange(newVal)
})
watch(pageSize, (newVal, oldVal) => {
  handlePageSizeChange(newVal)
})

function handlePageChange(val) {
  uid.value++;
  page.value = val;
  // clearSelection();
  getData();
}
function handlePageSizeChange(val) {
  uid.value++;
  // if (page.value !== 1) clearSelection();
  page.value = 1;
  pageSize.value = val;
  getData();
}
function handledbClick(row) {
  emit("dbClick", row);
}
function handleRowClick(row) {
  emit("rowClick", row);
}
function handleSelectionChange(...args) {
  emit("selection-change", ...args);
}
function handleSortChange(...args) {
  emit("sort-change", ...args);
}
function currentChange(...args) {
  emit("current-change", ...args);
}

const tableRender = () => {
  let pagination = null;
  if (props.paginationable) {
    pagination = (
      <el-pagination
        background={true}
        total={total.value}
        page-size={pageSize.value}
        current-page={page.value}
        page-sizes={pageSizes.value}
        layout="total, sizes, prev, pager, next"
        onUpdate:current-page={(newValue) => page.value = newValue}
        onUpdate:page-size={(newValue) => pageSize.value = newValue}
        // on-current-change={handlePageChange}
        // on-size-change={handlePageSizeChange}
      />
    );
  }
  return (
    <div class="bwt-table">
      <el-table
        v-loading={loading.value}
        ref="table"
        size={props.size}
        data={data.value}
        height={props.height}
        row-key={props.rowKey}
        row-class-name={props.rowClassName}
        row-style={props.rowStyle}
        header-row-class-name={props.headerRowClassName}
        highlight-current-row={props.highlightCurrentRow}
        lazy={props.lazy}
        load={props.load}
        tree-props={props.treeProps}
        on-current-change={currentChange}
        on-row-dblclick={handledbClick}
        on-row-click={handleRowClick}
        on-selection-change={handleSelectionChange}
        on-sort-change={handleSortChange}
        header-cell-style={props.headerCellStyle}
      >
        {props.columns.map((item, index) => {
          const render = item.render
            ? (props) =>
                item.render(
                  proxy.$parent ? proxy.$parent.$createElement : h,
                  props
                )
            : null;
          return (
            <el-table-column
              key={item.key}
              prop={item.key}
              width={item.width}
              sortable={item.sortable}
              min-width={item.minWidth}
              type={item.type}
              label={item.title}
              render-header={item.renderHeader}
              formatter={item.format || formatter}
              fixed={item.fixed}
              align={item.align || 'center'}
              selectable={item.selectable}
              reserve-selection={item.reserveSelection}
              show-overflow-tooltip={item.showOverflowTooltip}
            >
              {render}
            </el-table-column>
          );
        })}
      </el-table>
      {pagination}
    </div>
  );
};

defineExpose({
  search,
  getData,
  refresh
})
</script>

<style lang="scss" scope>
.bwt-table {
  margin: 0 12px 12px 12px;
  .el-pagination {
    margin-top: 12px;
    justify-content: flex-end;
  }
  .el-pagination.is-background .btn-prev,
  .el-pagination.is-background .btn-next,
  .el-pagination.is-background .el-pager li {
    margin: 0 1px;
  }
  .el-pagination.is-background .el-pager li:not(.disabled).active {
    color: #4c64f0;
  }
  &-operation {
    .el-link {
      margin-right: 8px;
      color: var(--el-color-primary);
      &.danger {
        color: red;
      }
    }
  }
}
</style>
